package com.yoso.thread.call;

import com.yoso.thread.MyThreadPool;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author shizejin
 * @date 2022/4/2
 * @description:
 */
@Slf4j
public class Test3 {
    public static void main(String[] args) {

        ExecutorService executorService = MyThreadPool.getInstance();
        ExecutorCompletionService<Integer> executorCompletionService = new ExecutorCompletionService(executorService);
        List<Callable<Integer>> list = new ArrayList<>();
        list.add(() -> {
            TimeUnit.SECONDS.sleep(5);
            System.out.println(" 5s ");
            return 5;
        });

        list.add(() -> {
            TimeUnit.SECONDS.sleep(1);
            System.out.println(" 1s ");
            return 1;
        });
        list.add(() -> {
            TimeUnit.SECONDS.sleep(8);
            System.out.println(" 8s ");
            return 8;
        });
        try {
//            List<Future<Integer>> futures = executorService.invokeAll(list);
//            System.out.println(futures);
            List<Integer> newList1  = new ArrayList<>();
            List<Future<Integer>> futureList = new ArrayList<>();
            for (Callable<Integer> integerCallable : list) {
                Future<Integer> submit = executorCompletionService.submit(integerCallable);
                futureList.add(submit);
            }
            System.out.println("任务提交完成");
            System.out.println("获取返回");
            for (Future<Integer> future : futureList) {
                Future<Integer> take = executorCompletionService.take();
                System.out.println(take.get());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
